/****************************************************************
 * bmp085.c														*
 * Hardware: BMP085												*
 * Created: 23.12.2013 08:17:00									*
 * Author: Cedomir Jovanovic									*
 ***************************************************************/ 

#include "bmp085.h"

void bmp085_get_altitude()
{
	bmp085_Convert(&temperature,&pressure);
	temp = (double) pressure/101325;
	temp = 1-pow(temp, 0.19029);
	altitude = round(44330*temp);
	temperature=temperature*0.1;

}

void bmp085_Calibration(void)
{
	temperature = 0;
	pressure=0;
	altitude=0;
	temp=0;
	
	ac1 = bmp085_ReadCal(0xAA);
	ac2 = bmp085_ReadCal(0xAC);
	ac3 = bmp085_ReadCal(0xAE);
	ac4 = bmp085_ReadCal(0xB0);
	ac5 = bmp085_ReadCal(0xB2);
	ac6 = bmp085_ReadCal(0xB4);
	b1  = bmp085_ReadCal(0xB6);
	b2  = bmp085_ReadCal(0xB8);
	mb  = bmp085_ReadCal(0xBA);
	mc  = bmp085_ReadCal(0xBC);
	md  = bmp085_ReadCal(0xBE);
	
		
}

short bmp085_ReadCal(unsigned char address)
{
	
	short result;
	
	i2c_start(BMP085_WRITE);
	i2c_write(address);
	i2c_stop();
	
	i2c_start(BMP085_READ);
	result=i2c_readAck()<<8;
	result|=i2c_readNak();
	i2c_stop();
	
	return result;
	
}

long bmp085_ReadTemp(void)
{
	
	long temperature = 0;
	
	i2c_start(BMP085_WRITE);
	i2c_write(0xF4);
	i2c_write(0x2E);
	i2c_stop();
	_delay_ms(10);
	
	temperature = bmp085_ReadCal(0xF6);
	
	return temperature;

}

long bmp085_ReadPres(void)
{
	
	long pressure = 0;
	
	i2c_start(BMP085_WRITE);
	i2c_write(0xF4);
	i2c_write(0x34);
	i2c_stop();
	_delay_ms(5);

	pressure = bmp085_ReadCal(0xF6);
	pressure &= 0x0000FFFF;
	
	return pressure;

}

void bmp085_Convert(long * temperature, long * pressure)
{
	
	//Temperatur Berechnung
	
	long ut, up;
	long x1, x2, b5;
	
	ut = bmp085_ReadTemp();
	ut = bmp085_ReadTemp();
	up = bmp085_ReadPres();
	up = bmp085_ReadPres();	
	
	x1 = ((long) ut -ac6) * ac5 >> 15;
	x2 = ((long) mc << 11) / (x1 + md);
	b5 = x1 + x2;
	*temperature = (b5 + 8) >> 4;
	
	

	//Druck Berechnung
	
	long b6, x3, b3, p;
	unsigned long b4, b7;
	
	b6 = b5 - 4000;
	x1 = (b2 * (b6 * b6 >> 12)) >> 11;
	x2 = ac2 * b6 >> 11;
	x3 = x1 + x2;
	b3 = (((int32_t) ac1 * 4 + x3) + 2)/4;
	x1 = ac3 * b6 >> 13;
	x2 = (b1 * (b6 *b6 >> 12)) >> 16;
	x3 = ((x1 + x2) + 2) >> 2;
	b4 = (ac4 * (unsigned long) (x3 + 32768)) >> 15;
	b7 = ((unsigned long) up - b3) * (50000 >> OSS);
	p = b7 < 0x80000000 ? (b7 * 2) / b4 : (b7 / b4) * 2;
	x1 = (p >> 8) * (p >> 8);
	x1 = (-7357 * p) >> 16;
	*pressure = p + ((x1 + x2 + 3791) >> 4);
	
	
}


